import _ from 'lodash'
import axios from 'axios'
import ApiList from './api.json'
import Vue from 'vue'
import {
    Message,
    MessageBox
} from 'element-ui'
Vue.component(MessageBox.name, MessageBox, Message)

let cancel;

/**
 * 接口请求
 * @param {*} key 
 */
const getUrl = (key) => {
    if (typeof ApiList[key] === 'undefined' || ApiList[key] === '') {
        return ''
    }
    var apiConfig = {
        "development": ApiList['dev-config'],
        "testing": ApiList['test-config'],
        "production": ApiList['prod-config']
    }
    return apiConfig[process.env.NODE_ENV] + ApiList[key]
}

/**
 * axios请求头
 * @param {*} data 
 */
const axiosHeaders = (data) => {
    if (data && data !== '') {
        return axios.interceptors.request.use(
            config => {
                config.headers['X-AUTH-TOKEN'] = `${data}`
                return config
            },
            err => {
                return Promise.reject(err)
            }
        )
    }
}

/**
 * 请求示例：api.post("get", api.getUrl("内部放置请求的方法名，格式见api.json文件内")).then(res => {});
 * @param {*} state 
 * @param {*} url 
 * @param {*} data 
 * @param {*} dataType 
 */
const post = (state, url, data, dataType = 'isJson') => {
    let postData = {}
    let _data = _.assign({}, data)
    if (dataType == 'isJson') {
        postData = data
    } else {
        _.forEach(_data, (val, key) => {
            if (['timeout'].indexOf(key) === -1) {
                postData[key] = val
            }
        })
    }
    if (state === 'get') {
        let idx = 0
        if (postData && postData !== '') {
            for (var key in postData) {
                if (idx === 0) {
                    url += '?' + key + '=' + postData[key]
                } else {
                    url += '&' + key + '=' + postData[key]
                }
                idx++
            }
        }
    }
    var formData = new FormData();
    if (dataType == "formData") {
        for (var key in postData) {
            formData.append(key, postData[key])
        }
    }
    let promise = new Promise((resove, reject) => {
        return axios({
            method: state,
            url: url,
            data: dataType == "formData" ? formData : postData,
            timeout: 8000, // 请求延时设置的8s
            headers: {
                'Content-Type': 'application/json',
                'epc-token': '', // 用户登录的token
            },
        }).then(function (resp) {
            let json = resp.data;
            //这一块用来处理请求回调 resove(resp)，如果有登录超时或未登录检测，可再加判断处理请求结果的回调
            if (json.code == 0) {
                resove(resp)
            } else {
                Message.error(json.msg);
                reject(json);
            }
        }).catch(function (err) {
            if (err.response && err.response.data) {
                Message.error(err.response.data.error);
                reject(err.response.data.error)
            } else {
                Message.error('请求超时');
            }
        })
    })
    return promise
}

/**
 * 时间格式化（年月日）
 * @param {*} time 
 * @param {*} i 
 */
const formateDate = function (time, i) {
    if (!time) {
        time = new Date()
    } else {
        time = new Date(time)
    }

    let y = time.getFullYear()
    let mo = time.getMonth() + 1
    let d = time.getDate()
    if (!i) {
        return y + '-' + (mo >= 10 ? mo : '0' + mo) + '-' + (d >= 10 ? d : '0' + d)
    } else {
        return y + (mo >= 10 ? mo : '0' + mo) + (d >= 10 ? d : '0' + d)
    }

}

/**
 * 时间格式化：年月日时分秒
 * @param {*} time 
 */
const formateTime = function (time) {
    if (!time) {
        return time
    }
    time = new Date(time)
    let y = time.getFullYear()
    let mo = time.getMonth() + 1
    let d = time.getDate()
    let h = time.getHours()
    let mi = time.getMinutes()
    let s = time.getSeconds()
    return y + '-' + (mo >= 10 ? mo : '0' + mo) + '-' + (d >= 10 ? d : '0' + d) + ' ' + (h >= 10 ? h : '0' + h) + ':' + (mi >= 10 ? mi : '0' + mi) + ':' + (s >= 10 ? s : '0' + s)
}

export default {
    getUrl,
    axiosHeaders,
    post,
    formateDate,
    formateTime,
    cancel: () => {
        cancel && cancel()
    }
}
